package com.ryan.mdp.service;

import org.springframework.core.NamedThreadLocal;

public class MdpContextHolder {

    @SuppressWarnings("rawtypes")
    private static final ThreadLocal currentContext = new NamedThreadLocal("Current Mdp Context");

    public static MdpContext currentContext() throws IllegalStateException {
        MdpContext context = (MdpContext) currentContext.get();
        if (context == null) {
            throw new IllegalStateException("Cannot find current context");
        }
        return context;
    }

    @SuppressWarnings("unchecked")
    public static Object setCurrentContext(MdpContext context) {
        MdpContext oldContext = (MdpContext) currentContext.get();
        if (context != null) {
            currentContext.set(context);
        } else {
            currentContext.remove();
        }
        return oldContext;
    }

    public static void resetContext() {
        currentContext.remove();
    }
}
